<template>
  <div v-if="isShowChart" ref="chartRef" style="width: 100%; height: 400px" />
  <px-empty v-else description="暂无数据" />
</template>
<script lang="ts" setup>
import { ref, onMounted, defineProps, watch, nextTick } from "vue";
import { http } from "@/utils/http";
import * as echarts from "echarts";
const chartRef = ref(null);

type ResultTable = {
  total?: number;
  data?: Array<any>;
};

const props = defineProps({
  date: {
    type: Array,
    default: () => []
  }
});
onMounted(() => {
  // const params = { typeId: "593", className: "MACHINE", devType: "PCW" };
  // // const params = { typeId: "593", className: "MACHINE", devType: "MAU" };
  // queryList(params).then(res => {
  //   console.log("res22222", res);
  //   createChart(res?.ffuList);
  // });
  // getData();
});
watch(
  () => props.date,
  newVal => {
    getData();
  }
);
//查询SPC指标列表
const queryList = (data?: object) => {
  return http.request<ResultTable>("post", `/operation/api/v1/operation/consumable/listAll`, {
    data
  });
};

// 查询数据
const queryPcwAllAPI = data => {
  return http.request("post", `/operation/api/v1/operation/algorithm/queryPcwAll`, {
    data
  });
};
const isShowChart = ref(false);

const getData = async () => {
  try {
    let installStart = props.date[0] ? props.date[0] + " 00:00:00" : getCurrentMonthF() + " 00:00:00";
    let installEnd = props.date[1] ? props.date[1] + " 23:59:59" : getCurrentMonthL() + " 23:59:59";
    let params = {
      typeId: "593",
      className: "MACHINE",
      devType: "PCW",
      // installStart: "2024-11-18 11:30:26",
      // installEnd: "2025-01-08 11:30:26"
      installStart: installStart,
      installEnd: installEnd
    };
    isShowChart.value = false;
    const res = await queryPcwAllAPI(params);
    let resultDTO = res?.resultDTO?.lifeList || [];
    isShowChart.value = true;
    nextTick(() => {
      createChart(resultDTO);
    });
  } catch (error) {
    console.log(error);
  }
};

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d: any = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

const createChart = ffuList => {
  // const option = getOption(ffuList);
  const option = getResultDTOOption(ffuList);
  if (chartRef.value) {
    const myChart = echarts.init(chartRef.value);
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
  }
};
const getOption = ffuList => {
  const seriesData = {
    lifecycle_exp: [],
    lifecycle_last: [],
    lifecycle_predict: [],
    lifecycle_use: [],
    avg: []
  };
  let list = [];
  for (let i = 0; i < ffuList.length; i++) {
    list.push(...ffuList[i].filters);
  }
  let xAxisDate = []; //X轴的时间坐标
  const dateYear = new Date().getUTCFullYear().toString().substr(2);
  const predictStart = list[0].lifecycle_predict - (list[0].lifecycle_exp - list[0].lifecycle_exp_left);
  const predictEnd = list[0].lifecycle_predict;
  const predictStep = (predictEnd - predictStart) / (list.length - 1);
  let predictList = [];
  //模拟实际使用寿命
  for (let i = 0; i < list.length; i++) {
    predictList.push(predictStart + predictStep * i);
  }

  for (let i = 0; i < list.length; i++) {
    xAxisDate.push(`${dateYear}/${i > 8 ? (i + 1).toString() : "0" + (i + 1).toString()}`);
    seriesData.lifecycle_exp.push(list[i].lifecycle_exp); //额定寿命
    seriesData.lifecycle_last.push(list[i].lifecycle_last); //上次寿命
    seriesData.lifecycle_use.push(predictList[i]); //实际使用寿命
    seriesData.lifecycle_predict.push(list[i].lifecycle_predict); //AI预测寿命
    seriesData.avg.push(0);
  }
  let series = [
    {
      name: "额定寿命",
      type: "line",
      yAxisIndex: 0,
      data: seriesData.lifecycle_exp
    },
    {
      name: "上次寿命",
      type: "line",
      yAxisIndex: 0,
      data: seriesData.lifecycle_last
    },
    {
      name: "实际使用寿命",
      type: "line",
      yAxisIndex: 0,
      lineStyle: {
        type: "dashed" // 设置为虚线
      },
      data: seriesData.lifecycle_use
    },
    {
      name: "预测寿命",
      type: "line",
      yAxisIndex: 0,
      data: seriesData.lifecycle_predict
    }
  ];
  let newOption = option;
  newOption.series = series;
  newOption.xAxis[0].data = xAxisDate;
  return newOption;
};

const getResultDTOOption = data => {
  const seriesData = {
    ratedValueAry: [], // 额定寿命
    aiValueAry: [], // 预测寿命
    actualValueAry: [], // 实际寿命
    lastActualValueAry: [] //上次寿命
  };
  let xAxisDate = []; //X轴的时间坐标
  for (let i = 0; i < data.length; i++) {
    let item = data[i];
    xAxisDate.push(item?.dateTimeResult?.substring(0, 10));
    seriesData.ratedValueAry.push(item?.ratedValue); //额定寿命
    seriesData.lastActualValueAry.push(item?.lastActualValue); //上次寿命
    seriesData.actualValueAry.push(item?.actualValue); //实际使用寿命
    seriesData.aiValueAry.push(item?.aiValue); //AI预测寿命
  }
  let series = [
    {
      name: "额定寿命",
      type: "line",
      yAxisIndex: 0,
      data: seriesData.ratedValueAry
    },
    {
      name: "上次寿命",
      type: "line",
      yAxisIndex: 0,
      data: seriesData.lastActualValueAry
    },
    {
      name: "实际使用寿命",
      type: "line",
      yAxisIndex: 0,
      lineStyle: {
        type: "dashed" // 设置为虚线
      },
      data: seriesData.actualValueAry
    },
    {
      name: "预测寿命",
      type: "line",
      yAxisIndex: 0,
      data: seriesData.aiValueAry
    }
  ];
  let newOption = option;
  newOption.series = series;
  newOption.xAxis[0].data = xAxisDate;
  return newOption;
};

//echart展示
const colors = ["#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de", "#3ba272", "#fc8452", "#9a60b4", "#ea7ccc"];
const option = {
  color: colors,
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross"
    }
  },
  grid: {
    left: "60"
  },
  legend: {
    data: ["额定寿命", "上次寿命", "实际使用寿命", "预测寿命"]
  },
  xAxis: [
    {
      type: "category",
      axisTick: {
        alignWithLabel: true
      },
      // prettier-ignore
      data: []
    }
  ],
  yAxis: [
    {
      type: "value",
      name: "单位：天",
      position: "left",
      alignTicks: true,
      offset: 0,
      axisLine: {
        show: true,
        lineStyle: {
          color: colors[0]
        }
      },
      axisLabel: {
        formatter: "{value}"
      }
    }
  ],
  series: []
};
</script>
<style lang="scss" scoped>
.chart-title {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  height: 32px;
}
</style>
